<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Http\Models\Ad;

class AdController extends Controller{

    public function index(Request $request)
    {
        //data不可数
        $data = Ad::orderBy("created_at","desc")->get();
        //$data = $data->paginate(20);
        return view("admin.ad.index",['data'=>$data,'active'=>'ad']);
    }

    public function create(Request $request)
    {
        return view('admin.ad.create',['active'=>'ad']);
    }

    public function store(Request $request){
        $ad = new Ad;
        $ad -> title = $request->input('title');
        $ad -> url = $request -> input('url');
        $ad -> cover = $request ->input('cover');
        $ad -> position = intval($request -> input('position'));

        //唯一
        $hasPostion = Ad::where(['position'=>$ad->position])->count();
        if($hasPostion){
            return $this->failure('/admin/ad','广告位置必须唯一');
        }

        $ad -> save();
        return redirect('/admin/ad');
    }

    public function edit($id){

        $banner = Ad::find($id);

        return view('admin.ad.edit',['banner'=>$banner,'active'=>'ad']);
    }


    public function update(Request $request,$id)
    {
        $ad = Ad::find($id);

        $ad -> title = $request->input('title');
        $ad -> url = $request -> input('url');
        $ad -> cover = $request ->input('cover');
        $ad -> position = intval($request -> input('position'));

        //唯一
        $hasPostion = Ad::where(['position'=>$ad->position])->where('id','<>',$ad->id)->count();
        if($hasPostion){
            return $this->failure('/admin/ad','广告位置必须唯一');
        }

        $ad->save();

        return redirect('/admin/ad');
    }

    public function delete($id)
    {
        $res = Ad::destroy($id);
        if($res) return view('success',['url'=>'/admin/ad']);

        return view('failure',['url'=>'/admin/ad']);
    }

}